<template>

    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name"/>
        </el-form-item>
        <el-form-item label="图片" prop="img">
            <TukuVue v-model="formData.img"></TukuVue>
        </el-form-item>
        <el-form-item label="排序" prop="seq">
            <el-input-number v-model="formData.seq" :min="1" :max="99"/>
        </el-form-item>
        <el-form-item label="父类" prop="parentId">
            <CategoryTreeVue v-model:modelValue="formData.parentId"></CategoryTreeVue>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(formRef)">
                修改
            </el-button>
        </el-form-item>
    </el-form>
</template>


<script setup lang="ts">
import {ref, onMounted, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {categoryApi} from '@/api'
import TukuVue from '@/components/Tuku.vue'
import {useRouter} from 'vue-router'
import {useRoute} from 'vue-router'
import CategoryTreeVue from "@/components/CategoryTree.vue";

const router = useRouter()
const route = useRoute()
const formRef = ref()

const formData = reactive({
    id: 0,
    name: '',
    img: '',
    seq: 0,
    parentId: 0
})
const categoryData = ref()
onMounted(() => {
    formData.id = Number(route.query.id)
    callOneCategoryApi()
})
const callOneCategoryApi = () => {
    categoryApi.select.call({id: formData.id}).then((res: any) => {
        formData.name = res[0].name
        formData.img = res[0].img
        formData.seq = res[0].seq
        formData.parentId = res[0].parentId
    })
}


const formSubmit = () => {
    categoryApi.update.call({
        id: formData.id,
        name: formData.name,
        img: formData.img,
        seq: formData.seq,
        parentId: formData.parentId
    }).then((res: any) => {
        ElMessage.success('修改成功')
        //
    })
}

const submitForm = async (formEl: any) => {
    if (!formEl) return
    await formEl.validate((valid: any, fields: any) => {
        if (valid) {
            formSubmit()
        } else {
            console.log('error submit!', fields)
        }
    })
}


const rules = reactive({
    name: [
        {required: true, message: '分类名称必填', trigger: 'blur'},
    ],
})


</script>